package com.edu.builder;

import com.edu.abstractI.ExerciseGenerate;
import com.edu.abstractI.Symbol;
import com.edu.abstractI.impl.*;
import com.edu.pojo.Exercise;
import com.edu.util.JsonUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

/**
 * @author five-five
 * @created 2021/11/21 - 15:57
 */
public class ExerciseBuilder {
    private ExerciseGenerate subtractGenerate = new SubtractExerciseGenerate(new SubtractSymbolImpl());
    private ExerciseGenerate addGenerate = new AddExerciseGenerate(new AddSymbolImpl());
    private ExerciseGenerate binaryGenerate = new BinaryExerciseGenerate();
    private ArrayList<Exercise> exerciseArrayList = new ArrayList<>();
    public final static String FILE_PATH = "jsons" + File.separator + "examination.json";

    public ExerciseBuilder generateAdd(int length) {
        exerciseArrayList.addAll(addGenerate.generateExercise(length));
        return this;
    }

    public ExerciseBuilder generateSubtract(int length) {
        exerciseArrayList.addAll(subtractGenerate.generateExercise(length));
        return this;
    }

    public ExerciseBuilder generateBinary(int length) {
        exerciseArrayList.addAll(binaryGenerate.generateExercise(length));
        return this;
    }

    public ArrayList<Exercise> getExerciseArrayList() {
        return exerciseArrayList;
    }

    /**
     * 开始一场标椎考试
     */
    public ExerciseBuilder startNormalExamination(int length) {
        ArrayList<Exercise> exerciseArrayList = this.generateAdd(length).generateBinary(length).generateSubtract(length).getExerciseArrayList();
        Scanner in = new Scanner(System.in);
        System.out.println("==========================================开始考试=========================================");
        int rightCount = 0;
        for (Exercise exercise : exerciseArrayList) {
            System.out.println(exercise.getLeft() + exercise.getSymbol().getSymbol() + exercise.getRight() + "=\t");
            int result = in.nextInt();
            if (result == exercise.getSymbol().calculate(exercise.getLeft(), exercise.getRight())) {
                rightCount++;
            }
            exercise.setResult(result);
        }
        System.out.println("======================================题目回答完毕=======================================");
        System.out.println("正确数为:" + rightCount);
        return this;
    }

    public File exerciseToFile() throws IOException {
        File file = new File(FILE_PATH);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        List<String> stringList = exerciseArrayList.stream().map(exercise -> {
            int isright = 0;
            if (exercise.getResult() == exercise.getSymbol().calculate(exercise.getLeft(), exercise.getRight())) {
                isright = 1;
            }
            return isright + "#" + exercise.getLeft() + exercise.getSymbol().getSymbol() + exercise.getRight() + "=" + exercise.getResult();
        }).collect(Collectors.toList());
        byte[] bytes = JsonUtil.objectToJson(stringList).getBytes(StandardCharsets.UTF_8);
        bos.write(bytes, 0, bytes.length);
        bos.flush();
        bos.close();
        return file;
    }

    public List<String> fileToExercise() throws IOException {
        File file = new File(FILE_PATH);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[1024 * 1024];
        StringBuilder sb = new StringBuilder();
        int len = -1;
        while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
            sb.append(new String(buffer, StandardCharsets.UTF_8));
        }
        bis.close();
        return JsonUtil.jsonToList(sb.toString(), String.class);
    }

    /**
     * @param correct 0:错误 1:正确
     * @return
     */
    public List<Exercise> getChooseProblem(int correct) throws Exception {
        List<String> stringList = fileToExercise();
        ArrayList<Exercise> exercises = new ArrayList<>(stringList.size());
        stringList.forEach(s -> {
            if (s.startsWith(correct + "")) {
                //left下标
                //right下标
                //符号下标
                //=下标
                Symbol symbol = null;
                boolean contains = s.contains("+");
                if (contains) {
                    symbol = new AddSymbolImpl();
                } else {
                    symbol = new SubtractSymbolImpl();
                }
                int symbol_index = !contains ? s.indexOf("-") : s.indexOf("+");
                int equal_index = s.indexOf("=");
                String left = s.substring(2, symbol_index);
                String right = s.substring(symbol_index + 1, equal_index);
                String result = s.substring(equal_index + 1);
                Exercise exercise = new Exercise();
                exercise.setLeft(Integer.parseInt(left));
                exercise.setRight(Integer.parseInt(right));
                exercise.setSymbol(symbol);
                exercise.setResult(Integer.parseInt(result));
                exercises.add(exercise);
            }
        });
        return exercises;
    }
}
